/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.CommonUtil;
import Common.Global;
import DAO.CollectionDAO;
import DAO.PriceHistoryDAO;
import DAO.TrackedProductDAO;
import hibernate.entity.Account;
import hibernate.entity.Collection;
import hibernate.entity.PriceHistory;
import hibernate.entity.TrackedProduct;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author NamDH
 */
public class ManageProductController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String url = "ManageProductController?btAction=ShowTrackedProduct";
        try {
            String action = request.getParameter("btAction");
            if (action.equals("ShowTrackedProduct")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    List<TrackedProduct> result = tpDAO.getTrackedProductbyAccount_Id(acc.getAccountID());
                    session.setAttribute("SHOWTRACKEDPRODUCT", result);
                    session.removeAttribute("SEARCHPRODUCT");
                    session.removeAttribute("SEARCHCOLLECTION");
                    response.sendRedirect(Common.Global.manageproduct);
                } else if (acc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("SearchProduct")) {
                String txtSearchProduct = request.getParameter("txtSearchProduct");
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    List<TrackedProduct> result = tpDAO.searchProductLikeNameByAccount(txtSearchProduct, acc.getAccountID());
                    if (result != null) {
                        session.setAttribute("SEARCHPRODUCT", result);
                        session.removeAttribute("SHOWTRACKEDPRODUCT");
                        session.removeAttribute("COLLECTION");
                    }
                    response.sendRedirect(Common.Global.manageproduct);
                } else if (acc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("showProductDetail")) {
                int productID = Integer.parseInt(request.getParameter("productDetailID"));
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    session.setAttribute("PRODUCTID", productID);
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    TrackedProduct trackedProduct = tpDAO.getTrackedProductbyProduct_ID(productID);
                    CollectionDAO colDAO = new CollectionDAO();
                    List<Collection> result1 = colDAO.getCollectionsbyAccount_Id(acc.getAccountID());
                    session.setAttribute("COLLECTION", result1);


                    PriceHistoryDAO phDAO = new PriceHistoryDAO();
                    double currentprice = phDAO.getLastPriceHistorybyTPID(productID);

                    Set<PriceHistory> phs = trackedProduct.getPriceHistories();
                    List<PriceHistory> bridge = new ArrayList<PriceHistory>();
                    bridge.addAll(phs);
                    List<PriceHistory> priceHistories = new ArrayList<PriceHistory>();
                    int flag = bridge.size() - 1;
                    if (phs.size() < 4) {
                        priceHistories.addAll(phs);
                        while (priceHistories.size() < 4) {
                            PriceHistory item = priceHistories.get(flag);
                            PriceHistory bonus = new PriceHistory(item.getPrice(), "");
                            if (priceHistories.size() == 3) {
                                bonus.setUpdatedDate(item.getUpdatedDate());
                            }
                            priceHistories.add(bonus);
                        }
                    } else if (phs.size() > 5) {
                        for (int i = 5; i > 0; i--) {
                            priceHistories.add(bridge.get(bridge.size() - i));
                        }
                    } else {
                        priceHistories.addAll(phs);
                    }
                    List recommendProduct = tpDAO.recommendProduct(trackedProduct.getProductName(), trackedProduct.getProductLink());
                    session.setAttribute("RCMPRODUCT", recommendProduct);
                    session.setAttribute("SHOWPRODUCTDETAIL", trackedProduct);
                    session.setAttribute("CURRENTPRICE", currentprice);
                    session.setAttribute("PRICEHISTORIES", priceHistories);
                    response.sendRedirect(Common.Global.manageproduct);
                } else if (acc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("SearchProductIndex")) {
                String txtSearchProduct = request.getParameter("txtSearchProductIndex");
                TrackedProductDAO tpDAO = new TrackedProductDAO();
                List<TrackedProduct> result = tpDAO.searchProductLikeName(txtSearchProduct);
                if (!result.isEmpty()) {
                    session.setAttribute("SEARCHPRODUCTINDEX", result);
                } else {
                    session.removeAttribute("SEARCHPRODUCTINDEX");
                    session.setAttribute("SEARCHPINDEXNOTFOUND", "Sorry our website don't have any products you want to find");
                }
                response.sendRedirect(Common.Global.indexpage);
            } else if (action.equals("deleteProduct")) {
                int productID = Integer.parseInt(request.getParameter("deleteProductID"));
                PriceHistoryDAO phDAO = new PriceHistoryDAO();
                boolean checkDeletePrice = phDAO.deletePricebyProductID(productID);
                if (checkDeletePrice) {
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    boolean check = tpDAO.deleteProduct(productID);
                    if (check) {
                        session.setAttribute("DELETEPROSUC", "You deleted product successfully!!!");
                        response.sendRedirect(url);
                    } else {
                        session.setAttribute("DELETEPROERR", "You deleted product failed!!!");
                        response.sendRedirect(url);
                    }
                } else {
                    session.setAttribute("DELETEPROFAIL", "Sorry!!! You can't delete product!!!");
                    response.sendRedirect(url);
                }
            } else if (action.equals("showProductDetailIndex")) {
                int productID = Integer.parseInt(request.getParameter("productDetailIDIndex"));
                TrackedProductDAO tpDAO = new TrackedProductDAO();
                TrackedProduct trackedProduct = tpDAO.getTrackedProductbyProduct_ID(productID);
                PriceHistoryDAO phDAO = new PriceHistoryDAO();
                double currentprice = phDAO.getLastPriceHistorybyTPID(productID);
                Set<PriceHistory> phs = trackedProduct.getPriceHistories();
                List<PriceHistory> bridge = new ArrayList<PriceHistory>();
                bridge.addAll(phs);
                List<PriceHistory> priceHistories = new ArrayList<PriceHistory>();
                int flag = bridge.size() - 1;
                if (phs.size() < 4) {
                    priceHistories.addAll(phs);
                    while (priceHistories.size() < 4) {
                        PriceHistory item = priceHistories.get(flag);
                        PriceHistory bonus = new PriceHistory(item.getPrice(), "");
                        if (priceHistories.size() == 3) {
                            bonus.setUpdatedDate(item.getUpdatedDate());
                        }
                        priceHistories.add(bonus);
                    }
                } else if (phs.size() > 5) {
                    for (int i = 5; i > 0; i--) {
                        priceHistories.add(bridge.get(bridge.size() - i));
                    }
                } else {
                    priceHistories.addAll(phs);
                }
                List recommendProduct = tpDAO.recommendProduct(trackedProduct.getProductName(), trackedProduct.getProductLink());
                session.setAttribute("RCMPRODUCTINDEX", recommendProduct);
                session.setAttribute("SHOWPRODUCTDETAILINDEX", trackedProduct);
                session.setAttribute("CURRENTPRICEINDEX", currentprice);
                session.setAttribute("PRICEHISTORIESINDEX", priceHistories);
                response.sendRedirect(Common.Global.indexpage);
            } else if (action.equals("updateDesiredPrice")) {
                int productID = ((Integer) session.getAttribute("PRODUCTID")).intValue();
                if (productID != 0) {
                    double desiredPrice = 0;
                    String dPrice = request.getParameter("txtNewDesiredPrice");
                    if (!dPrice.equals("")) {
                        desiredPrice = Double.parseDouble(dPrice);
                    }
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    boolean check = tpDAO.updateDesiredPrice(desiredPrice, productID);
                    if (check) {
                        session.setAttribute("UPDATEPRISUC", "You updated desired price successfully!!!");
                    } else {
                        session.setAttribute("UPDATEPRIERR", "You updated desired price failed!!!");
                    }
                    response.sendRedirect(url);
                } else if (productID == 0) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("addItem")) {
                int trackedProductID = ((Integer) session.getAttribute("PRODUCTID")).intValue();
                if (trackedProductID != 0) {
                    double desiredPrice = 0;
                    String dPrice = request.getParameter("txtNewDesiredPrice");
                    if (!dPrice.equals("")) {
                        desiredPrice = Double.parseDouble(dPrice);
                    }
                    TrackedProductDAO tpDAO = new TrackedProductDAO();
                    tpDAO.updateDesiredPrice(desiredPrice, trackedProductID);
                    try {
                        String collection = request.getParameter("ddlCollectionList");
                        if (!collection.equals("")) {
                            CollectionDAO colDAO = new CollectionDAO();
                            Collection col = colDAO.getCollectionByName(collection);
                            int collectionID = col.getCollectionID();
                            boolean check = colDAO.addItem(collectionID, trackedProductID);
                            if (check) {
                                session.setAttribute("SAVEPROSUC", "You updated new information for product successfully!!!");
                            } else {
                                session.setAttribute("SAVEPROERR", "You updated new information for product failed!!!");
                            }
                            response.sendRedirect(url);
                        } else if (collection.equals("")) {
                            session.setAttribute("SAVEPROFAIL", "You updated desired price successfully!!!");
                            response.sendRedirect(url);
                        }
                    } catch (NullPointerException ex) {
                        session.setAttribute("SAVEPROFAIL", "You updated desired price successfully!!!");
                        response.sendRedirect(url);
                    }

                } else if (trackedProductID == 0) {
                    response.sendRedirect(Common.Global.loginpage);
                }

            } else if (action.equals("trackProduct")) {
                double desiredPrice = 0;
                Account account = (Account) session.getAttribute("ACCOUNT");
                if (account != null) {
                    String dPrice = request.getParameter("desired_price");
                    if (!dPrice.equals("")) {
                        desiredPrice = Double.parseDouble(dPrice);
                    }
                    String urlP = request.getParameter("productLink");
                    String productName = request.getParameter("productName");
                    double productPrice = Double.parseDouble(request.getParameter("productPrice"));
                    String productImage = request.getParameter("productImage");


                    TrackedProductDAO trackedProductDAO = new TrackedProductDAO();
                    trackedProductDAO.addNewTrackedProduct(account.getAccountID(), urlP, productName, productPrice, productImage, desiredPrice);
                    response.sendRedirect(Global.showproduct);
                } else {
                    response.sendRedirect(Global.loginpage);
                }

            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
